﻿using Microsoft.AspNetCore.Mvc;
using SimulationCenter.Models;
using SimulationCenter.Schedulers;
using SimulationCenter.Tasks;
using SimulationCenter.Tasks.Svrs;
using System.Threading.Tasks;

namespace SimulationCenter.Controllers
{
    /// <summary>
    /// 任务
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class TaskController : ControllerBase
    {
        private readonly ITaskSvr _taskSvr;
        private readonly ScScheduleManager _scheduleManager;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="taskSvr"></param>
        public TaskController(ITaskSvr taskSvr, ScScheduleManager scheduleManager)
        {
            _taskSvr = taskSvr;
            _scheduleManager = scheduleManager;
        }

        /// <summary>
        /// 创建任务
        /// </summary>
        /// <param name="name">任务名称</param>
        /// <param name="description">任务描述</param>
        /// <param name="targetDevices">关联设备号, 多个设备号使用逗号(,)分割</param>
        /// <param name="subscriptionRange">爬取公众号范围</param>
        /// <param name="targetSubscriptions">指定公众号（subscriptionRange 为 All:1 时忽略）, 多个公众号使用逗号(,)分割</param>
        /// <param name="msgRange">爬取消息范围</param>
        /// <param name="lastDays">爬取最后几天的消息（msgRange 为 All:0 时忽略 ）</param>
        /// <param name="runMode">运行方式</param>
        /// <param name="cron">轮询 cron （runMode 为 Once:0 时忽略）</param>
        /// <returns>任务实例</returns>
        [HttpPost]
        public async Task<Resp> Create(
            string name, string description,
            string targetDevices,
            ScSubscriptionRange subscriptionRange, string targetSubscriptions = null, 
            ScMsgRange msgRange = ScMsgRange.All, int? lastDays = null, 
            ScLoopMode runMode = ScLoopMode.Once, string cron = null
            )
        {
            var scTask = await _taskSvr.CreateTask(name, description, subscriptionRange, targetDevices, status: ScTaskStatus.Running,
                targetSubscriptions, msgRange, lastDays, runMode, cron);

            await _scheduleManager.AddScTaskSchedule(scTask);

            return Resp.Success(scTask);
        }
    }
}